package com.andrewchatham.pony;

import android.content.ComponentName;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;

class SyncServiceConnection implements ServiceConnection {
  public final static String TAG = "SyncServiceConnection";
  private ISyncService mService = null;
  
  SyncServiceConnection() {
  }
  
  public boolean startSync() {
    waitForConnected();
    try {
      mService.startSync();
      return true;
    } catch (RemoteException e) {
      Log.e(TAG, e.toString());
      return false;
    }
  }
  
  public boolean stopSync() {
    try {
      mService.stopSync();
      return true;
    } catch (RemoteException e) {
      Log.e(TAG, e.toString());
      return false;
    }
  }
  
  private synchronized void waitForConnected() {
    while (mService == null)
      try {
        wait();
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
  }

  public synchronized void onServiceConnected(ComponentName className, IBinder service) {
    Log.d(TAG, "Connected");
    mService = ISyncService.Stub.asInterface(service);
    notifyAll();
  }

  public void onServiceDisconnected(ComponentName name) {
    Log.d(TAG, "Disconnected");
    mService = null;
  }
}